package com.example.demoa;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements IOnDelListener{
    private RecyclerView rlvStu;
    private ArrayList<Student> studentArrayList = new ArrayList<>();
    private StuAdapter adapter;
    private Button btuAddStu;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iniStudentArryList();

        adapter = new StuAdapter(MainActivity.this,studentArrayList,MainActivity.this);

        rlvStu = findViewById(R.id.rlv_stu);


        rlvStu.setLayoutManager(new LinearLayoutManager(this));
        rlvStu.setAdapter(adapter);

        btuAddStu = findViewById(R.id.btu_addStu);
        btuAddStu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivityForResult(intent,1001);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.e("MainActivity",
                "requestCode = " + requestCode + "resultCode ="+resultCode);

        //<Bug>:防止data为空白指针时，程序崩溃ii。
        if (data ==null){
            return;
        }

        String name = data.getStringExtra("NAME");
        int age = data.getIntExtra("AGE",0);
        int imgId = data.getIntExtra("IMG",R.drawable.img1);

        String no = "18001";
        Student s = new Student(no,name,age,imgId);
        studentArrayList.add(s);

        //刷新页面
        adapter.notifyDataSetChanged();

    }

    private void iniStudentArryList() {
        Student s1 = new Student("18001","张一",20,R.drawable.img1);
        Student s2 = new Student("18002","张二",21,R.drawable.img2);
        Student s3 = new Student("18003","张三",22,R.drawable.img3);
        Student s4 = new Student("18004","张四",23,R.drawable.img4);
        Student s5 = new Student("18005","张五",24,R.drawable.img5);

        studentArrayList.add(s1);
        studentArrayList.add(s2);
        studentArrayList.add(s3);
        studentArrayList.add(s4);
        studentArrayList.add(s5);

    }


    @Override
    public void del(int i) {
        studentArrayList.remove(i);
    }
}
